package com.ruoyi.common.utils;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.condition.BaseCondition;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.sql.SqlUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.Locale;

/**
 * 分页工具类
 * 
 * @author ruoyi
 */
public class PageUtils extends PageHelper
{
    /**
     * 设置请求分页数据
     */
    public static void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * fucking the stupid thinking of PageHelper
     * @param condition
     * @param <E>
     */
    public static <E extends BaseCondition> void collectPageParams(E condition){
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            Sort sort  = null;
            if(orderBy != null && !"".equals(orderBy)){
                String [] ob = orderBy.split("\\s+");
                if(ob.length == 1 || ob[1].toLowerCase().equals("desc")){
                    sort = Sort.by(Sort.Direction.DESC, ob[0]);
                }else{
                    sort = Sort.by(Sort.Direction.ASC, ob[0]);
                }
            }
            // dont ask me why -1
            if (sort != null) {
                condition.setPageable(PageRequest.of(pageNum - 1, pageSize, sort));
            } else {
                condition.setPageable(PageRequest.of(pageNum - 1, pageSize));
            }
        }
    }
}
